import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.Charset;

public class Server {
    public static void main(String[] args) throws IOException {
        ServerSocket serverSocket = new ServerSocket(6666);
        System.out.println("server is running");
        for(;;){
            Socket sock = serverSocket.accept();
            System.out.println("connection from " + sock.getRemoteSocketAddress());
            Thread t = new Handler(sock);
            t.start();
        }
    }
}

class Handler extends Thread {
    Socket sock;

    public Handler(Socket sock){
        this.sock = sock;
    }

    @Override
    public void run(){
        try (InputStream input = sock.getInputStream()) {
            try (OutputStream output = sock.getOutputStream()){
                handle(input,output);
            }
        } catch (Exception e) {
            try {
                sock.close();
            } catch (IOException ioe) {
                System.out.println("关闭线程失败");
            }
            System.out.println("客户端断开连接");
        }
    }

    private void handle(InputStream input, OutputStream output) throws IOException {
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(output, Charset.defaultCharset()));
        BufferedReader reader = new BufferedReader(new InputStreamReader(input, Charset.defaultCharset()));
        writer.write("hello\n");
        writer.flush();
        for(;;){
            String s = reader.readLine();
            if (s.equals("bye")) {
                writer.write("bye\n");
                writer.flush();
                break;
            }
            writer.write("ok" + s + "\n");
            writer.flush();
        }

    }
}
